package com.slipper.system.codeless.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.slipper.system.codeless.bo.VariableBO;
import com.slipper.system.codeless.dao.VariableDao;
import com.slipper.core.transaction.ReadTransactional;
import com.slipper.core.transaction.WriteTransactional;
import com.slipper.util.Tool;
import com.slipper.util.UUID;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@ReadTransactional
public class VariableService {
    @Resource
    private VariableDao variableDao;

    public VariableBO queryBy(String id) {
        return variableDao.queryBy(id);
    }
    
    public List<VariableBO> queryList(VariableBO bo) {
        return variableDao.queryList(bo);
    }
    
    public PageInfo<VariableBO> queryPage(VariableBO bo) {
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(variableDao.queryList(bo));
    }
    
    @WriteTransactional
    public int save(VariableBO bo) {
        int result;
        bo.setUpdateTime(System.currentTimeMillis());
        if (Tool.isNotBlank(bo.getId())) {
            bo.setUpdateTime(System.currentTimeMillis());
            result = variableDao.update(bo);
        } else {
            bo.setId(UUID.getUUID());
            bo.setUpdateTime(System.currentTimeMillis());
            bo.setCreateTime(System.currentTimeMillis());
            result = variableDao.insert(bo);
        }
        return result;
    }

    @WriteTransactional
    public void saveList(List<VariableBO> variableList) {
        if (variableList == null) return;

        variableList.forEach(variable -> {
            if (variableDao.queryBy(variable.getId()) != null) {
                variable.setUpdateTime(System.currentTimeMillis());
                variableDao.update(variable);
            } else {
                variable.setUpdateTime(System.currentTimeMillis());
                variable.setCreateTime(System.currentTimeMillis());
                variableDao.insert(variable);
            }
        });
    }

    @WriteTransactional
    public int delete(VariableBO bo) {
        return variableDao.delete(bo);
    }

    public long queryTotal(VariableBO bo) {
        PageHelper.startPage(0, 0);
        return new PageInfo<>(variableDao.queryList(bo)).getTotal();
    }

    public boolean existsName(String id, String code) {
        return variableDao.existsName(id, code) > 0;
    }

    public VariableBO queryByName(String name) {
        return variableDao.queryByName(name);
    }

}
